<template>
  <div>
    <div class="app-container">
      <h-table-list
        border
        type="local"
        :page-sizes="[10,20]"
        :data="deviceBasic.records"
        :columns="columns"
        :pagination-info="paginationInfo"
        :form-options="formOptions"
        @size-change="handleSizeChange"
        @select="selectRows"
      >
        <ListOpearteButton />
        <template
          slot="preview-column"
          slot-scope="scope"
        >
          <div :class="'circle-'+scope.row.state" /><span>{{ scope.row.state |formatState }}</span>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify
      :visible.sync="dialogFormVisible"
      title="下载设备标识码"
      @cancel="cancel"
      @update="updateDialog"
    >
      <IdentifyContent ref="identify" />
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ListOpearteButton from '@/components/AllButton/button2'
import tableButton from '@/components/AllButton/button3'
import DownloadIdentify from '@/components/FormDialog'
import { mapGetters } from 'vuex'
import IdentifyContent from './component/identifyContent'
import data from './const'

export default {
  name: 'DeviceBasic',
  components: {
    DownloadIdentify,
    IdentifyContent,
    Pagination,
    tableButton,
    ListOpearteButton
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      hasSelectRows: [],
      dialogFormVisible: false,
      loadList: false,
      paginationInfo: {
        sizeChange: e => {
          console.log(e)
        },
        currentChange: e => {
          this.$store.dispatch('deviceBasic/setListSearchParams', {
            current: e
          })
          this.getList(
            Object.assign({}, this.$store.state.deviceBasic.listSearchParams)
          )
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: '搜索',
        showResetBtn: true,
        searchParamsHandler: () => {
          console.log('搜索')
          this.getList(this.$store.state.deviceBasic.listSearchParams)
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)

          this.$store.dispatch('deviceBasic/setListSearchParams', params)
        },
        resetBtnCallback: () => {
          this.$store.dispatch('deviceBasic/setListSearchParams', {})
          // this.getList(this.$store.state.deviceBasic.listSearchParams);
          this.getList()
        },
        forms: [
          {
            prop: 'deviceName',
            label: '设备名称',
            defaultValue: 'A11',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100
          },
          {
            prop: 'assetCode',
            label: '固定资产编码',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100
          },

          {
            prop: 'assetNumber',
            label: '设备编号',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100
          },
          {
            prop: 'deviceClass',
            label: '设备类别',
            itemType: 'select',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100,
            options: [
              { value: 'A', label: 'A' },
              { value: 'B', label: 'B' },
              { value: 'C', label: 'C' }
            ]
          },
          {
            prop: 'typeId',
            label: '设备分类',
            itemType: 'cascader',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100,
            options: [
              { value: 'A', label: 'A' },
              { value: 'B', label: 'B' },
              { value: 'C', label: 'C' }
            ]
          },
          {
            prop: 'organId',
            label: '使用部门',
            itemType: 'cascader',
            labelPosition: 'right',
            itemWidth: 200,
            labelWidth: 100,
            options: []
          },

          {
            prop: 'responsible',
            label: '责任人',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100
          },
          {
            prop: ['startProductDate', 'endProductDate'],
            label: '投产日期',
            itemType: 'daterange',
            itemWidth: 200,
            labelPosition: 'right'
          },
          {
            prop: 'assetValue',
            label: '设备原值',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100
          },
          {
            prop: 'deviceModel',
            label: '型号',
            itemWidth: 200,
            labelPosition: 'right',
            labelWidth: 100
          },
          {
            prop: 'state',
            label: '单据状态',
            itemType: 'select',
            options: [
              { value: 3, label: '停用' },
              { value: 2, label: '启用' },
              { value: 1, label: '审批失败' },
              { value: 0, label: '待审批' }
            ]
          }
        ]
      },
      columns: [
        { type: 'selection', label: '序号' },
        { prop: 'deviceName', label: '设备名称' },
        { prop: 'assetCode', label: '固定资产编码' },

        { prop: 'assetNumber', label: '设备编号' },
        { prop: 'deviceClass', label: '设备类别' },
        { prop: 'typeId', label: '设备分类' },
        {
          prop: 'organName',
          label: '使用部门'
        },

        { prop: 'responsible', label: '责任人' },
        { prop: 'productDate', label: '投产日期', filter: 'formatDate' },
        { prop: 'assetValue', label: '设备原值' },
        { prop: 'deviceModel', label: '型号' },

        {
          prop: 'status',
          label: '状态',
          minWidth: 180,
          slotName: 'preview-column'
        },
        {
          prop: 'operate',
          label: '操作',
          minWidth: 180,
          slotName: 'operate-column',
          fixed: 'right'
        }
      ],
      column2s: [],
      tableData: []
    }
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(['deviceBasic', 'app'])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等  用于处理页面切换的操作
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop
      const data = this.$store.state.deviceBasic.listSearchParams
      e.defaultValue = data[key] || ''
      return e
    })),
    // this.submitHandler=this.searchWithParams
    this.$store
      .dispatch(this.$store_url_button, {
        add: this.add,
        export: this.export,
        delete: this.delete,
        edit: this.edit,
        detail: this.detail,
        using: this.using,
        useless: this.useless,
        downloadTemplete: this.downloadTemplete,
        download1: this.downloadIdentify
      })
      .then(async() => {
        const department = this.listTotree(
          this.$store.state.app.allCode.department
        )
        const assetType = this.listTotree(
          this.$store.state.app.allCode.assetType
        )
        // (this.formOptions.forms)[5].options=obj
        this.$set(this.formOptions.forms[5], 'options', department)
        this.$set(this.formOptions.forms[4], 'options', assetType)
        console.log(this.formOptions, '转换结果')
        // console.log(this.$store.state)
        this.getList() // 表格数据
      })

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    // 勾选
    selectRows(selection, row) {
      console.log(selection)
      console.log(row)
      this.hasSelectRows = selection
    },
    // 对于多级下拉的code组装需要按照elementUi的组件格式,数据从vuex获取
    listTotree(list) {
      var listData = [...list]
      var map = {}
      var node
      var tree = []
      var i
      for (i = 0; i < listData.length; i++) {
        map[listData[i].id] = listData[i]
        // listData[i]["value"]= listData[i].typeId||listData[i].organId
        // listData[i]["label"]= listData[i].typeName|| listData[i].organName
        // listData[i].children = [];
      }
      for (i = 0; i < listData.length; i++) {
        node = listData[i]
        if (node.parentId == 0) {
          tree.push(node)
        } else {
          // map[node.parentId].children?map[node.parentId].children:map[node.parentId].children=[] //这里是为了配合ele组件
          // map[node.parentId].children.push(node);
          // delete node.children
        }
      }
      return tree
    },
    // 自定义该业务模块下的按钮方法
    // 启用
    using(row) {
      this.$confirm(`确认启用设备台账？`, '启用设备台账', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store
          .dispatch('deviceBasic/useDevice', row)
          .then(response => {
            this.getList(this.$store.state.deviceBasic.listSearchParams)
          })
          .catch(() => {})
      })
    },
    // 停用
    useless(row) {
      this.$confirm(
        `确认停用设备台账？

停用后该设备相关计划将自动停用`,
        '停用设备台账',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$store
          .dispatch('deviceBasic/uselessDevice', row)
          .then(response => {
            this.getList(this.$store.state.deviceBasic.listSearchParams)
          })
          .catch(() => {})
      })
    },
    add(row) {
      console.log(row)
      this.$router.push('/device-basic/component/edit/add')
      this.getList(this.$store.state.deviceBasic.listSearchParams)
    },
    edit(row) {
      // this.$store.dispatch("deviceBasic/downloadTemplete",row.assetId);
      localStorage.setItem('/device-basic/component/edit/index', row.id)
      this.$router.push('/device-basic/component/edit/index')
      console.log('edit')
    },
    downloadIdentify(row) {
      console.log('下载设备标识卡', this.hasSelectRows)
      if (this.hasSelectRows.length == 0) {
        this.$message('请选择设备')
      } else {
        this.dialogFormVisible = true
      }
    },
    async downloadTemplete(ids) {
      console.log('下载导出模板')
      const download = await this.$store.dispatch(
        'deviceBasic/downloadTemplete'
      )
      // window.open(download.)
      console.log(download)
      window.open(download)
    },
    delete(row) {
      console.log(row)
      this.$confirm(`确认删除？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$store
            .dispatch('deviceBasic/deleteDeviceInfo', row.id)
            .then(response => {
              // this.$message({
              //   type: "success",
              //   message: "删除成功!"
              // });
              this.getList()
            })
            .catch(() => {
              // this.$message({
              //   type: "info",
              //   message: "删除失败"
              // });
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    update() {},
    detail(row) {
      console.log(row)

      localStorage.setItem('/device-basic/component/detail/index', row.id)
      this.$router.push('/device-basic/component/detail/index')
    },
    import() {},
    async export() {
      console.log('导出')
      console.log(this.hasSelectRows)
      const data = this.hasSelectRows
      const res = await this.$store.dispatch('deviceBasic/exportFile', data)
      window.open(res.data)
    },
    // 弹窗的关闭
    cancel() {
      console.log('关闭弹窗')
      this.dialogFormVisible = false
    },
    // 更新弹窗数据
    updateDialog() {
      console.log('更新并关闭弹窗', this.$refs.identify.checkedGroups)
      console.log('选择对象', this.hasSelectRows)
      const that = this
      const dataArray = []
      const data = this.hasSelectRows.map(e => {
        const item = {}
        Object.keys(e).forEach(function(key) {
          if (that.$refs.identify.checkedGroups.includes(key)) {
            item[key] = e[key]
          }
          item.assetId = e.assetId
          if (that.$refs.identify.checkedGroups.includes('qrcode')) {
            item.qrcode = true
          } else {
          }
        })
        dataArray.push(item)
      })
      this.$store
        .dispatch('deviceBasic/downloadIdentify', dataArray)
        .then(res => {
          window.open(res.data, '_blank')
        })

      this.dialogFormVisible = false
    },
    // 搜索按钮
    searchWithParams() {
      console.log('搜索')
    },
    async getList(args) {
      // this.listLoading = true
      await this.$store.dispatch('deviceBasic/requestDeviceList', args)
      this.paginationInfo.total = this.$store.state.deviceBasic.total
    },
    handleFilter(args) {
      this.listQuery.page = 1
      this.getList(args)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
<style >
</style>

